<?php
namespace app\service;


use app\model\GoodsPeriodModel;
use app\model\OrderModel;
use app\model\OrderPeriodProcessModel;
use support\facade\Logger;
use const support\CORRECT;
use const support\DENY;
use const support\order_status_1;
use const support\order_status_8;

class OrderPeriodProcessService{

    //成团检测
    public static function clusterDetection(): bool
    {
        //本次日志关联标识
        $logId=md5(uniqid('ct'));
        //获取明日日0点时间
        $time=strtotime('tomorrow');
        //获取符合营期ID
        $goodsPeriod=GoodsPeriodModel::where([
            'goods_period_date'=>$time,
            'status'           =>CORRECT
        ])->pluck('min_group_num','id')->toArray();
        if (empty($goodsPeriod)){
            Logger::app(sprintf('成团检测(%s):%s未检测到成团信息',$logId,$time));
            return true;
        }
        foreach ($goodsPeriod as $id=>$minNum){
            //检测订单是否以满足最小成团人数
            $orderNum=OrderModel::where([
                'goods_period_id'   =>$id,
                'status'            =>CORRECT,
                'is_refund'         =>CORRECT
            ])->whereIn('order_status',[order_status_8,order_status_1])->count();
            if ($orderNum>=$minNum){
                $ret=OrderPeriodProcessModel::updateOrInsert([
                    'goods_period_id'=>$id,
                    'status'         =>CORRECT
                ],[
                     'create_time'=>time(),
                     'update_time' =>time()
                ]);
            }else{
                $ret=OrderPeriodProcessModel::updateOrInsert([
                    'goods_period_id'=>$id,
                ],[
                    'status'     =>DENY,
                    'create_time'=>time(),
                    'update_time' =>time()
                ]);
            }
            Logger::app(sprintf('成团检测(%s):检测到成团信息',$logId),'info',[$ret,$id,$orderNum]);
        }
        return true;
    }

}